﻿using SuperX.Common.APIManager;
using SuperX.Common.Object;
using SuperX.Common.PlugIn;
using SuperX.Common.Respository;
using log4net.Plugin;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text;

namespace SuperX.Common
{
    /// <summary>
    /// 启动整个服务的入口
    /// </summary>
    public abstract class HostService : BasicObject, IHostService
    {
        //
        public abstract override string ServiceType { get; set; }

        //
        public bool IsEnable { get; set; }

        //
        public SuperX.Common.PlugIn.RunMode RunMode { get; set; }

        //
        [JsonIgnore]
        public ModuleContext ModuleContext { get; set; }

        //
        public string FileName { get; set; }

        //
        [JsonIgnore]
        public string FullFileName
        {
            get
            {
                if (ModuleContext != null && !Path.IsPathRooted(FileName))
                {
                    return Path.Combine(ModuleContext.HostDir, FileName);
                }
                return FileName;
            }
        }

        //
        [JsonIgnore]
        public virtual IAPIController APIController { get; set; }

        //
        [JsonIgnore]
        public bool IsRunning { get; protected set; }

        //
        [JsonIgnore]
        public ControllerStatus Status { get; set; }

        //
        [JsonIgnore]
        public IRepository Repository { get; set; }

        //
        [JsonIgnore]
        public override string FullName
        {
            get
            {
                return Name;
            }
        }

        //
        public bool Load<T>(string fileName, out T model) where T : BasicObject, new()
        {
            FileName = fileName;
            Repository = new JsonRepository(FileName);
            Repository.Load(typeof(T));
            model = (Repository.Model as T) ?? new T();
            if (model == null)
                return false;
            model.Parent = this;
            return true;
        }

        //
        public virtual bool Save()
        {
            return SaveAs(FileName);
        }

        //
        public bool Save<T>(string fileName, T model) where T : BasicObject, new()
        {
            if (model == null)
                return false;
            Repository = new JsonRepository(fileName) { Model = model };
            Repository.Save();
            return true;
        }

        public abstract bool Init();

        public abstract bool Start();

        public abstract bool Stop();

        public abstract bool Exit();

        public abstract bool Load(string fileName);

        public abstract bool SaveAs(string fileName);
    }
}